//
//  ThirdVC.swift
//  甜言蜜语
//
//  Created by yingli_yanfa_liuxingyu on 16/11/16.
//  Copyright © 2016年 wl. All rights reserved.
//

import UIKit

class ThirdVC: UIView {
    @IBOutlet weak var iv: UIImageView!
    @IBOutlet weak var btn: UIButton!
    
    //var timer: NSTimer!//定义定时器
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    struct Example {
        static let secondLaunchView = NSBundle.mainBundle().loadNibNamed("ThirdVC", owner: nil, options: nil).first as! ThirdVC
        
        static var timer: NSTimer!//定时器
        
        static var timeTick: Int = 0
        
        static var urlStr: String!
        
        static var model: ADImageModel?
        
    }
   static func gdf() {
       let urlStr = String(format: "%@indexads", BaseUrl)
       DataTool.getADinfo(urlStr ,completionHandler: ({(newModel) in
       guard newModel != nil else {
       return
    }
       Example.model = newModel
       if Example.model?.msg == "查询成功" {
        ThirdVC.showSencondAtWindow(Example.model?.imgsrc, time: Example.model?.timelength, url: Example.model?.url)
       }
    }))

    
    }
    static func showSencondAtWindow(image: String?, time: String?, url: String?) {
        
        guard let imageStr = image  else {
            return
        }
        Example.urlStr = url!
        Example.secondLaunchView.btn.layer.masksToBounds = true
        Example.secondLaunchView.btn.layer.cornerRadius = 25
        Example.secondLaunchView.btn.setTitle("\(time!)秒", forState: UIControlState.Normal)
        Example.secondLaunchView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)
        
        let window = UIApplication.sharedApplication().keyWindow
        
        
        Example.secondLaunchView.iv.sd_setImageWithURL(NSURL(string: imageStr)!)
        
        window?.addSubview(Example.secondLaunchView)
        
        Example.timeTick = Int(time!)!
        
        Example.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(ThirdVC.removeViewkl), userInfo: nil, repeats: true)
    }
    
    @IBAction func btnClicked(sender: UIButton) {
        
        Example.secondLaunchView.removeFromSuperview()
    }
    @IBAction func backGroundIvSelected(sender: UIButton) {
        
        Example.secondLaunchView.removeFromSuperview()
        
        let dic = ["url":Example.urlStr]
        NSNotificationCenter.defaultCenter().postNotificationName("adClicked_noti", object: dic)
    }
    deinit {
        Example.timer?.invalidate()
        //        print("SecondLaunchView--deinit")
    }
    
    static func removeViewkl() {
         Example.timeTick -= 1
        
        if Example.timeTick == 0 {
            Example.secondLaunchView.removeFromSuperview()
        }
        
        let str: String = "\(Example.timeTick)"
        Example.secondLaunchView.btn.setTitle("\(str)秒", forState: .Normal)
       
        
    }

}
